import { createStore } from 'vuex'
import createPersistedState from "vuex-persistedstate";
import {login} from '../api/login'
export default createStore({
  state: {
    token:null,
    userInfo:{},
    newusers:[
      {
        username: 'admin',
        password: '123456',
        nickname:'管理员',
        photo:'/images/photo0.png'
      },
      {
        username: 'taozongqian',
        password: '123456',
        nickname:'终离宴',
        photo:'/images/photo2.png'
      },
      {
        username: 'chenfei',
        password: '123456',
        nickname:'陈菲',
        photo:'/images/photo1.png'
      },
      {
        username: 'duyuxuan',
        password: '123456',
        nickname:'椰汁西米露',
        photo:'/images/photo4.png'
      },
      {
        username: 'jizishuori',
        password: '123456',
        nickname:'吉子',
        photo:'/images/photo3.png'
      },
    ],
  },
  plugins: [createPersistedState()],
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo,
    newusers:state => state.newusers,
  },
  mutations: {
    // 登陆保存token
    loginSuccess(state, payload) {
      state.token = payload.token
      state.userInfo = payload.options
     
    },
    // 重置token
    reset(state) {
      state.token = null
      state.userInfo = ''
    },
    // 注册的新用户保存
    conserveNewuser(state, payload){
      const {newusername,newpassword,newnickname} = payload
      const result =  state.newusers.filter(item=>{
        if(item.username === newusername){
            return item
        }
      })
      if(result[0]){
         throw '该用户已存在！'
      }else{
        const user = {
          username: newusername,
          password: newpassword,
          nickname:newnickname,
          photo:'/images/photo5.png'
          }
         // @ts-ignore
         state.newusers.push(user)
         return {message:'注册成功'}
      }
     
    }
  },
  actions: {
        async loginAction(context, payload) {
      try { 
        const result = await login(payload)
        
        //@ts-ignore
        if (result.token) { // 登录成功
          context.commit('loginSuccess', result)
          return true
        } else { // 登录失败
          context.commit('reset')
          return false
        }
      } catch (error) {
        // 出现异常，则重置用户登录状态数据
        console.warn(error)
        context.commit('reset')
        return false
      }
    },
  },
  modules: {
  }
})
